package com.controller;

import com.entity.Grade;
import com.service.GradeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
public class GradeController {

    @Autowired
    GradeService gradeService;


    /*
    查询年级所有信息
    */
    @RequestMapping("/gradeList")
    public String finGradeAll(Model model) {
        List<Grade> gradeList = gradeService.findAll();
        model.addAttribute("glist", gradeList);

//        System.out.println(gradeList);

        return "pages/gradeList";
    }


    /*
    按照ID值查询
     */
    @RequestMapping(value = "/findGradeById",method = RequestMethod.GET)
    public ModelAndView findGradeById(@RequestParam("gid") int gid){
        Grade grade =gradeService.findGradeById(gid);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("pages/gradeList");
        mv.addObject("grade",grade);
        return mv;
    }

    /*
    多对一查询
     */
    @RequestMapping("/findGradeWithStudentById")
    public Grade findGradeWithStudentById(@RequestParam("gid") int gradeID){
        return  gradeService.findGradeWithStudentById(gradeID);
    }

    /*
   添加保存年级信息
    */
    @RequestMapping(value = "/saveGrade",method = RequestMethod.POST)
    public String saveGrade(Grade grade){
        gradeService.saveGrade(grade);

        //System.out.println(1/0);//事务管理，抛出异常
        //重定向
        return "redirect:/gradeList";

    }
    /*
    添加信息
     */
    @RequestMapping("/addGrade")
    public String addGrade(){
        return "pages/GradeAdd";
    }

    /*
    删除数据
     */
    @RequestMapping("/delGradeById" )
    public  String  delGradeById(@RequestParam("gid") int gid){

        gradeService.delGradeById(gid);
        return "redirect:/gradeList";
    }

    /*
    删除多条数据
     */
    @RequestMapping("/delGradeByIds")
    @ResponseBody
    public String delGradeByIds(@RequestParam("gids[]") String[] gids){
        gradeService.delGradeByIds(gids);
        return "ok";

    }
    /*
    更新数据
     */
    @RequestMapping("/updateGradeById")
    public String updateGradeById(@RequestParam("gid") int gid,Model model){
        Grade grade = gradeService.findGradeById(gid);
        model.addAttribute("grade",grade);
        return "pages/gradeUpdate" ;
    }

    /*
     更新保存数据
     */
    @RequestMapping("/updateSaveGradeById")
    public String updateSaveGradeById(Grade grade){
        gradeService.updateGradeById(grade);
        return "redirect:/gradeList" ;
    }
}
